﻿var LocalStroageControl = function () {

    this.isLocalStorage = window.localStorage ? true : false;

    this.set = function (key, value, overwrite) {
        if (this.isLocalStorage) {
            var bl = this.isExist(key);
            if (bl) {
                if (overwrite) {
                    window.localStorage.setItem(key, value);
                }
                else {
                    alert("key:[" + key + "] is exist and don't replace it!");
                }
            } else {
                window.localStorage.setItem(key, value);
            }
        }
        else {
            return;
        }
    }

    this.get = function (key) {
        if (this.isLocalStorage) {
            return window.localStorage.getItem(key);
        }
        else {
            return null;
        }
    }

    /* exist -->return true, not exist -->return false*/
    this.isExist = function (key) {
        var bl = false;
        var keys = this.GetAllKeys();
        for (var i = 0; i < keys.length; i++) {
            if (key == keys[i]) {
                bl = true;
                break;
            }
        }
        return bl;
    }

    this.remove = function (key) {
        if (this.isLocalStorage) {
            localStorage.removeItem(key);
        }
        else {
            return;
        }
    }

    this.GetAllKeys = function () {
        var arrKey = new Array();
        for (var i in localStorage) {
            arrKey.push(i);
        }
        return arrKey;
    }

    this.GetAllValues = function () {
        var arrVal = new Array();
        var arrKey = this.GetAllKeys();
        for (var i = 0; i < arrKey.length; i++) {
            arrVal.push(this.get(arrKey[i]));
        }
        return arrVal;
    }

    this.getAllLocalStroage = function () {
        var arrKey = new Array();
        var arrVal = new Array();
        var json = "";
        for (var i in localStorage) {
            arrKey.push(i);
        }
        if (arrKey.length == 0) {
            alert("there are no localStorages in your computer!");
        }
        else {
            for (var i = 0; i < arrKey.length; i++) {
                arrVal.push(this.get(arrKey[i]));
            }
            json = "[";
            for (var i = 0; i < arrKey.length; i++) {
                json += "{";
                json += arrKey[i] + ":" + "'" + arrVal[i] + "'";
                json += "}";
                json += ",";
            }
            json = json.substring(0, json.lastIndexOf(','));
            json += "]";
        }

        return json;
    }
}